package me.yricky.usbhid

import me.yricky.OSUtils
import java.io.File

class UsbHid {
    private external fun nGetDevices():List<HidDevice>
    private external fun nEnableLog(enable:Boolean)

    var enableLog = false
        set(value) {
            nEnableLog(value)
            field = value
        }

    init {
        nEnableLog(false)
    }

    fun getDevices() = nGetDevices().associateBy { it.path }.values.toList()


    companion object {
        init {
            val libName = when(OSUtils.hostOs){
                OSUtils.OS.MacOS ->{
                    "libyruhb.dylib"
                }
                OSUtils.OS.Linux ->{
                    "libyruhb.so"
                }
                OSUtils.OS.Windows->{
                    "libyruhb.dll"
                }
                else ->{
                    throw RuntimeException("暂不支持当前系统！")
                }
            }
            ClassLoader.getSystemResource(libName).openStream().use { fis ->
                val yruhbFile = File.createTempFile("yruhb","lib")
                yruhbFile.deleteOnExit()
                yruhbFile.outputStream().use { fos ->
                    val buf = ByteArray(4096)
                    var len = fis.read(buf)
                    while (len > 0){
                        fos.write(buf,0,len)
                        len = fis.read(buf)
                    }
                }
                System.load(yruhbFile.absolutePath)
            }
        }
    }
}